# -*- coding:utf-8 -*-
from application import app
from flask import request,redirect,g
from common.models.User import User
from common.libs.user.UserService import UserService
from common.libs.UrlManager import UrlManager
import re
from common.libs.LogService import LogService

#拦截器
@app.before_request
def before_request():
    ignore_urls = app.config['IGNORE_URLS']
    ignore_check_login_urls = app.config['IGNORE_CHECK_LOGIN_URLS']
    path = request.path
    #正则表达式模式
    pattern = re.compile('%s' % "|".join(ignore_check_login_urls))
    #如果匹配直接中断不需要验证
    if pattern.match(path):
        return 
    #登录验证    
    user_info = check_login()
    g.current_user = None

    #如果用户登录 绑定到全局g变量
    if user_info:
        g.current_user = user_info

    #加入日志
    LogService.addAccessLog()

    #正则表达式模式
    pattern = re.compile('%s' % "|".join(ignore_urls))
    #如果匹配直接中断不需要验证
    if pattern.match(path):
        return 

    if not user_info:
        return redirect(UrlManager.buildUrl("/user/login"))

    return 



'''
判断用户是否已经登录
'''

def check_login():
    #取到cookie
    cookies = request.cookies
    auth_cookie = cookies[app.config['AUTH_COOKIE_NAME']] if app.config['AUTH_COOKIE_NAME'] in cookies else None
    # app.logger.info(auth_cookie)
    if auth_cookie is None:
        return False
    #split 字符串切个成列表 以#号分割  0是授权码 1是用户的uid
    auth_info = auth_cookie.split("#")
    if len(auth_info) != 2:
        return False
    try:
        #查询用户信息是否存在 会抛出一个异常
        user_info = User.query.filter_by(uid=auth_info[1]).first()
    except Exception:
        return False

    if user_info is None:
        return False
    
    #如果授权码不等于传递用户信息生成的加密串也认为是伪造
    if auth_info[0] != UserService.geneAuthCode(user_info):
        return False

    if user_info.status != 1:
        return False

    return user_info



